//mainwindow.cpp
#include <QApplication>
#include <QHeaderView>
#include <QFileDialog>
#include <QTableWidgetItem>
#include <QAction>
#include <QMenuBar>
#include <QFile>
#include <QInputDialog>
#include <QTextStream>
#include <string>
#include <QList>
#include "encrypter.h"
#include "Hex.h"
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setupMenu();
    setupTable();
    setupInterface();

    connect(this, SIGNAL(lastItemClicked(int)),
            table, SLOT(insertRow(int)));
    connect(actExport, SIGNAL(triggered()),
            this, SLOT(eventExport()));
    connect(actImport, SIGNAL(triggered()),
            this, SLOT(eventImport()));
    connect(actClear, SIGNAL(triggered()),
            table, SLOT(clearContents()));
    connect(this, SIGNAL(signalClean()),
            table, SLOT(clearContents()));
	connect(actAboutQt, SIGNAL(triggered()),
			qApp, SLOT(aboutQt()));
	connect(actExit, SIGNAL(triggered()),
			qApp, SLOT(quit()));
}

MainWindow::~MainWindow()
{

}

void MainWindow::setupMenu()
{
    menuFile = menuBar()->addMenu("&File");
	menuEdit = menuBar()->addMenu("&Edit");
	menuHelp = menuBar()->addMenu("&Help");

    actImport = new QAction("&Import...", this);
    actExport = new QAction("&Export...", this);
	actExit   = new QAction("Exit", this);
    actClear  = new QAction("Clear", this);
	actAbout  = new QAction("About", this);
	actAboutQt = new QAction("About Qt", this);

    menuFile->addAction(actImport);
    menuFile->addAction(actExport);
	menuFile->addSeparator();
	menuFile->addAction(actExit);
	menuHelp->addAction(actAbout);
	menuHelp->addAction(actAboutQt);
    menuEdit->addAction(actClear);
}

void MainWindow::setupTable()
{
    QStringList list;
    list<<"Usernames"<<"Passwords"<<"Memos";

    table = new QTableWidget(1, 3, this);
    table->setHorizontalHeaderLabels(list);
    table->horizontalHeader()->setStretchLastSection(true);
}

void MainWindow::setupInterface()
{
    setWindowTitle("iLockIt");
    setMinimumSize(WIDTH, HEIGHT);
    setCentralWidget(table);
}

void MainWindow::keyReleaseEvent(QKeyEvent* event)
{
    if (table->currentRow() == table->rowCount() - 1)
        emit lastItemClicked(table->currentRow() + 1);
}

void MainWindow::eventExport()
{
    encrypter msg;
    std::string username, password, memos;
    bool ok;
    std::string key;
    QString user, pw, memo;
    QString fileName;
    QString qKey = QInputDialog::getText(this, "Private key", "Enter your key:", QLineEdit::Password, "", &ok); //get the key from input dialog

    if (!ok || qKey.isEmpty()) return;

    key = qKey.toAscii().data();

    fileName = QFileDialog::getSaveFileName(this, "Save File", "./untitled.pwd", "Password File (*.pwd);;Text File (*.txt)"); //get file name from file dialog
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return;
    QTextStream out(&file);

    for (int i = 0; i < table->rowCount() - 1; i++) //loop thru the table rows
    {
        if (table->item(i, 0) != 0 && table->item(i, 1) != 0 && table->item(i, 0)->text() != "" && table->item(i, 1)->text() != "") //if the cell items are not empty, process export
        {
            user = table->item(i, 0)->text().trimmed();  //get user name and password 
            pw   = table->item(i, 1)->text().trimmed();
            username = user.toAscii().data();
            password = pw.toAscii().data();
            username = Hex::encode(username); //encode user name and password to Hex string 
            username = msg.encrypt(&username[0], &key[0]); //then encrypt it.
            password = Hex::encode(password); 
            password = msg.encrypt(&password[0], &key[0]);             
            out<<QString(&username[0])<<";"<<QString(&password[0]);
            if (table->item(i, 2) != 0 && table->item(i, 2)->text() != "")  //if memos is not empty, do encryption and encode on memos
            {															    //else append a new line
                memo = table->item(i, 2)->text().trimmed();
                memos = memo.toAscii().data();
                memos = Hex::encode(memos);
				memos = msg.encrypt(&memos[0], &key[0]);
                out<<";"<<QString(&memos[0])<<"\n";
            }else out<<"\n";
        }
    }
    file.close();
}

void MainWindow::eventImport()
{
    bool ok;
    QString fileName;
    QString user, pw, qKey, memo;
    string username, password, key, memos;
    QList<QStringList> list;
    encrypter msg;

    fileName = QFileDialog::getOpenFileName(this, "Open File", "./", "Password File (*.pwd);;Text File (*.txt)");
    if (fileName.isEmpty()) return;

    qKey = QInputDialog::getText(this, "Private key", "Enter your key:", QLineEdit::Password, "", &ok);
    if (qKey.isEmpty() || !ok) return;
    key = qKey.toAscii().data();

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
    QTextStream in(&file);

    while (!in.atEnd())
    {
        QString line = in.readLine();
        list.push_back(line.split(";"));
    }
    emit signalClean();
    table->setRowCount(list.size());
    for (int i = 0; i < list.size(); i++)
    {
        username = list[i][0].toAscii().data();
        username = msg.decrypt(&username[0], &key[0]); //decrypt it
        username = Hex::decode(username); //then decode the Hex string
        password = list[i][1].toAscii().data();
        password = msg.decrypt(&password[0], &key[0]); 
        password = Hex::decode(password); 

        QTableWidgetItem* newItem  = new QTableWidgetItem(QString(&username[0]), QTableWidgetItem::Type);
        QTableWidgetItem* newItem2 = new QTableWidgetItem(QString(&password[0]), QTableWidgetItem::Type);
        table->setItem(i, 0, newItem);
        table->setItem(i, 1, newItem2);

        if (list[i].size() == 3)
        {
            memos = list[i][2].toAscii().data();
            memos = msg.decrypt(&memos[0], &key[0]);
			memos = Hex::decode(memos);
            QTableWidgetItem* newItem3 = new QTableWidgetItem(QString(&memos[0]), QTableWidgetItem::Type);
            table->setItem(i, 2, newItem3);
        }
    }
}
